# -*- encoding: utf-8 -*-

"""
------------------------------------------
@File       : coroutine_await.py
@Author     : maixiaochai
@Email      : maixiaochai@outlook.com
@CreatedOn  : 2021/9/17 11:43
------------------------------------------
    之前的例子一直在使用 asyncio.gather() 函数来执行协程函数，
    还有一个 asyncio.wait() 函数，它的参数是协程的列表
    asyncio.wait，不推荐这种写法，因为将来的 Python版本将会移除这种方法
"""
from time import time
from asyncio import sleep, get_event_loop, wait


async def test_a(x):
    print('in test a')
    await sleep(3)
    print('resuming a')
    return x


async def test_b(x):
    print('in test b')
    await sleep(1)
    print('resuming b')
    return x


async def main():
    start = time()

    done, pending = await wait([test_a(1), test_b(2)])
    print("done: ", list(done))
    print("pending", list(pending))
    print(list(done)[0].result)

    time_cost = round(time() - start, 2)
    print(f"Time cost: {time_cost} s")


if __name__ == '__main__':
    """
        这里，先执行了 test_a 函数，然后再执行了 test_b 函数，是串行的依次执行的，并没有像我们想象中的并发执行
        Out:
            in test b
            in test a
            E:\Code\github\multiTasking\others\coroutine_await.py:35: DeprecationWarning: The explicit passing of coroutine objects to asyncio.wait() is deprecated since Python 3.8, and scheduled for removal in Python 3.11.
              done, pending = await wait([test_a(1), test_b(2)])
            resuming b
            resuming a
            done:  [<Task finished name='Task-3' coro=<test_a() done, defined at E:\Code\github\multiTasking\others\coroutine_await.py:18> result=1>, <Task finished name='Task-2' coro=<test_b() done, defined at E:\Code\github\multiTasking\others\coroutine_await.py:25> result=2>]
            pending []
            <built-in method result of _asyncio.Task object at 0x00000216536C6520>
            Time cost: 3.0 s
    """
    loop = get_event_loop()
    loop.run_until_complete(main())
